<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/**
 * Basketball extension for Joomleague
 * @version $Id: eventsstats.php 102 2008-03-01 00:26:19Z julien.vonthron $
 * @package JlgBasketballExtension
 * @copyright Copyright (C) 2007 Julien Vonthron. All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 * JlgBasketballExtension is free software and parts of it may contain or be derived from the
 * GNU General Public License or other free or open source software licenses.
 * 
 * contact: julien.vonthron[at]gmail.com 
 *   
 * Joomleague is a League Management and Prediction Game for Joomla!
 * Homepage: http://www.joomleague.de 
 *  
 */
?>

<?php

Class BasketballModelEventsStats {

  /**
   * returns an object with eventType's id as key
   *
   * @param int $project_id
   * @param int $event_type_id
   * @return array of events type objects
   */
  function getEventTypes( $project_id, $event_type_id=0 )
  {
    global $database;
    if ( !$project_id ) return null;
    
    $query = 'SELECT et.id AS etid, etj.eventtype_id AS id, et.* 
              FROM #__joomleague_eventtypes AS et
  	          INNER JOIN #__joomleague_et_joomleague AS etj ON et.id = etj.eventtype_id
  	          LEFT JOIN #__joomleague_position_eventtype pet ON pet.eventtype_id = et.id
  	          WHERE etj.project_id = '.$project_id;
  	          
  	if ($event_type_id > 0) $query.=" AND etj.eventtype_id = $event_type_id";
  	
  	// sort
  	$query.=' ORDER BY pet.ordering';
  	
  	$database->setQuery($query);
  	
  	return $database->loadObjectList("etid");
  }
  
  /**
   * returns array of object (stat / player_id) in decreasing order
   *
   * @param int $project_id
   * @param int $event_id
   * @param int $limit
   * @param int $limitstart
   * @return objects array
   */
  function getEventsRanking($project_id, $event_id, $limit=10, $limitstart=0)
  {
  	global $database, $overall_config;
  	if ( !$project_id ) return null;
  	
    switch ($event_id)
    {
      // per games stats
      case $overall_config['event_ppg']:
        $rows = $this->getPerGameStatRanking($project_id, $overall_config['event_points'], $limit, $limitstart);
        // restrict precision
        if ( $rows )
        {
          foreach ($rows as $k =>$row) {
            $rows[$k]->p = sprintf('%.1f', $rows[$k]->p);
          }
        }
        break;
      case $overall_config['event_rpg']:
        $rows = $this->getPerGameStatRanking($project_id, $overall_config['event_rebounds'], $limit, $limitstart);
        // restrict precision
        if ( $rows )
        {
          foreach ($rows as $k =>$row) {
            $rows[$k]->p = sprintf('%.1f', $rows[$k]->p);
          }
        }
        break;
      case $overall_config['event_apg']:
        $rows = $this->getPerGameStatRanking($project_id, $overall_config['event_assists'], $limit, $limitstart);
        // restrict precision
        if ( $rows )
        {
          foreach ($rows as $k =>$row) {
            $rows[$k]->p = sprintf('%.1f', $rows[$k]->p);
          }
        }
        break;
      case $overall_config['event_spg']:
        $rows = $this->getPerGameStatRanking($project_id, $overall_config['event_steals'], $limit, $limitstart);
        // restrict precision
        if ( $rows )
        {
          foreach ($rows as $k =>$row) {
            $rows[$k]->p = sprintf('%.1f', $rows[$k]->p);
          }
        }
        break;
      case $overall_config['event_bpg']:
        $rows = $this->getPerGameStatRanking($project_id, $overall_config['event_blocks'], $limit, $limitstart);
        // restrict precision
        if ( $rows )
        {
          foreach ($rows as $k =>$row) {
            $rows[$k]->p = sprintf('%.1f', $rows[$k]->p);
          }
        }
        break;
      // percentage stats
      case $overall_config['event_3pt_per']:
        $rows = $this->getRatioStatRanking( $project_id, 
                                              $overall_config['event_3pt_made'],
                                              $overall_config['event_3pt_attempts'], 
                                              $limit, $limitstart);
        // restrict precision
        if ( $rows )
        {
          foreach ($rows as $k =>$row) {
            $rows[$k]->p = sprintf('%.3f',$rows[$k]->p);
          }
        }
        break;
      case $overall_config['event_ft_per']:
        $rows = $this->getRatioStatRanking( $project_id, 
                                              $overall_config['event_ft_made'],
                                              $overall_config['event_ft_attempts'], 
                                              $limit, $limitstart);
        // restrict precision
        if ( $rows )
        {
          foreach ($rows as $k =>$row) {
            $rows[$k]->p = sprintf('%.3f',$rows[$k]->p);
          }
        }
        break;
      case $overall_config['event_fg_per']:
        $rows = $this->getRatioStatRanking( $project_id, 
                                              $overall_config['event_fg_made'],
                                              $overall_config['event_fg_attempts'], 
                                              $limit, $limitstart);
        // restrict precision
        if ( $rows )
        {
          foreach ($rows as $k =>$row) {
            $rows[$k]->p = sprintf('%.3f',$rows[$k]->p);
          }
        }
        break;
      default:
        $rows = $this->getTotalStatRanking($project_id, $event_id, $limit, $limitstart);
        break;
    }
	  
		if ( $rows )
		{
  		// Now we add rank field to rows
      // the first is the first...
      $rows[0]->rank = 1;
  		
  		// now, the following rows
  		for ( $x = 1; $x < count( $rows ); $x++ ) 
      {
  			$row = $rows[$x];
  			if ( $row->p == $rows[$x-1] ) { //same stat, same rank
          $row->rank = $rows[$x-1]->rank;
        }
  			else {
          $row->rank = $x+1;
        }
		  }
		}
		return $rows;
  }
  
  /**
   * returns array of object (total stat / player_id) in decreasing order
   *
   * @param int $project_id
   * @param int $event_id
   * @param int $limit
   * @param int $limitstart
   * @return objects array
   */
  function getTotalStatRanking($project_id, $event_id, $limit=10, $limitstart=0)
  {
  	global $database;
  	if ( !$project_id ) return null;
  	
    $query = 'SELECT SUM(me.event_sum) AS p, 
                      pt.id as player_id
              FROM #__joomleague_match_events AS me
              INNER JOIN #__joomleague_playertool AS pt USING (project_id, player_id)
              WHERE me.project_id =  '.$project_id
            . ' AND me.event_type_id =  '.$event_id
            . ' GROUP BY me.player_id, pt.team_id ORDER BY p DESC '
            . ' LIMIT ' . $limitstart . ', ' . $limit;
	  $database->setQuery($query);
	  
	  return $database->loadObjectList();
  }
  
  /**
   * returns array of object (per game stat / player_id) in decreasing order
   *
   * @param int $project_id
   * @param int $event_id
   * @param int $limit
   * @param int $limitstart
   * @return objects array
   */
  function getPerGameStatRanking($project_id, $event_id, $limit=10, $limitstart=0)
  {
  	global $database;
  	if ( !$project_id ) return null;
  	
  	// sub request for event total
    $sub_event = 'SELECT  mp.player_id, SUM(me.event_sum) AS total_event
  			                  FROM #__joomleague_match_events AS me 
  			                  INNER JOIN #__joomleague_match_players AS mp USING (match_id, player_id)
  			                  WHERE  me.event_type_id = '.$event_id 
  			                 .' AND me.project_id = '.$project_id	                          
	                       .' GROUP BY mp.player_id' ;
	                       
  	// sub request for games played
	  $sub_games_played = "SELECT  mp.player_id, COUNT(*) AS games_played
	                        FROM #__joomleague_match_players AS mp
	                        INNER JOIN #__joomleague_matches AS m USING (match_id)
	                        WHERE m.project_id = $project_id		                          
	                        GROUP BY mp.player_id";
  			                    
  	$query = 'SELECT (total_event / games_played) AS p, pt.id AS player_id
                  FROM #__joomleague_playertool AS pt
                  INNER JOIN ('.$sub_event.') AS se USING (player_id)
                  INNER JOIN ('.$sub_games_played.') AS gp USING (player_id)
                  WHERE games_played > 0 AND pt.project_id = '.$project_id 
              . ' ORDER BY (total_event/games_played) DESC'
              . ' LIMIT ' . $limitstart . ', ' . $limit;
                  
	  $database->setQuery($query);
	  
    return $database->loadObjectList();
  }
  
  /**
   * returns array of object (per game stat / player_id) in decreasing order
   *
   * @param int $project_id
   * @param int $event_id
   * @param int $limit
   * @param int $limitstart
   * @return objects array
   */
  function getRatioStatRanking($project_id, $dividend_event_id, $divisor_event_id, $limit=10, $limitstart=0)
  {
  	global $database;
  	if ( !$project_id ) return null;
  	
  	// sub request for dividend event total
    $sub_dividend = 'SELECT  mp.player_id, SUM(me.event_sum) AS dividend
  			                  FROM #__joomleague_match_events AS me 
  			                  INNER JOIN #__joomleague_match_players AS mp USING (match_id, player_id)
  			                  WHERE  me.event_type_id = '.$dividend_event_id 
  			                 .' AND me.project_id = '.$project_id	                          
	                       .' GROUP BY mp.player_id' ;
	                       
  	// sub request for divisor event total
    $sub_divisor = 'SELECT  mp.player_id, SUM(me.event_sum) AS divisor
  			                  FROM #__joomleague_match_events AS me 
  			                  INNER JOIN #__joomleague_match_players AS mp USING (match_id, player_id)
  			                  WHERE  me.event_type_id = '.$divisor_event_id 
  			                 .' AND me.project_id = '.$project_id	                          
	                       .' GROUP BY mp.player_id' ;
  			                    
  	$query = 'SELECT (dividend / divisor) AS p, pt.id AS player_id
                  FROM #__joomleague_playertool AS pt
                  INNER JOIN ('.$sub_dividend.') AS sd USING (player_id)
                  INNER JOIN ('.$sub_divisor.') AS sdv USING (player_id)
                  WHERE divisor > 0 AND pt.project_id = '.$project_id 
              . ' ORDER BY (dividend / divisor) DESC'
              . ' LIMIT ' . $limitstart . ', ' . $limit;
                  
	  $database->setQuery($query);
	  
    return $database->loadObjectList();
  }

  /**
   * returns an array of players info objects
   *
   * @param array int $playertool_ids
   * @return array
   */
  function getPlayersInfo( $playertool_ids )
  {  	
    global $database;
    
    $query = ' SELECT pt.id AS ptid, pt.team_id, pt.player_id, '
                  . ' p.firstname, p.lastname,'
                  . ' t.name AS team_name, t.short_name AS team_short
                  FROM #__joomleague_playertool AS pt
                  INNER JOIN #__joomleague_players AS p ON (p.id = pt.player_id)
                  INNER JOIN #__joomleague_teams AS t ON (t.id = pt.team_id)
                  WHERE pt.id IN (' . implode( ", ", $playertool_ids ). ') ';
    $database->setQuery($query);
    
    return $database->loadObjectList('ptid');
  }
}
?>
